import random
import sys
import pandas as pd
from pandas import DataFrame
sys.path.append ('../')
import data
from data import Data


class EmotionAnalysis(): #实现情绪判断功能

    def __init__(self,mode,identity) -> None:
        self.ActionData = None
        self.TextData = None
        self.Action_EmotionModel = None #行为-情绪模型 
        self.Text_HiddenModel = None #文本-情绪模型
        self.Hidden_ActivatingModel_A = None #生气时情绪-诱因模型
        self.Hidden_ActivatingModel_S = None #伤心时情绪-诱因模型
        self.Hidden_ActivatingModel_F = None #焦虑时情绪-诱因模型
        self.Activating_SolutionModel_A = [] #生气时诱因-解决模型组
        self.Activating_SolutionModel_S = [] #伤心时诱因-解决模型组
        self.Activating_SolutionModel_F = [] #焦虑时诱因-解决模型组
        self.sample = None #行为样本
        self.text_sample = None #文本样本
        self.UserData = None
        self.UnTaggedAction = None
        self.UnTaggedText = None
        self.OM = None
        self.solution_start = 0
        self.solution_num = 0
        self.identity = identity
        self.text_input = ''

        self.OM = Data.ObjMemory()

        path = '../data/' + mode + '/TrainAction.pkl'
        self.ActionData = self.OM.LoadObj(path)

        path = '../data/' + mode + '/TrainText.pkl'
        self.TextData = self.OM.LoadObj(path)

        path = '../model/' + mode + '/Action_EmotionModel.pkl'
        self.Action_EmotionModel = self.OM.LoadObj(path)

        path = '../model/' + mode + '/Text_HiddenModel.pkl'
        self.Text_HiddenModel = self.OM.LoadObj(path)

        path = '../model/' + mode + '/Hidden_ActivatingModel_A.pkl'
        self.Hidden_ActivatingModel_A = self.OM.LoadObj(path)

        path = '../model/' + mode + '/Hidden_ActivatingModel_S.pkl'
        self.Hidden_ActivatingModel_S = self.OM.LoadObj(path)

        path = '../model/' + mode + '/Hidden_ActivatingModel_F.pkl'
        self.Hidden_ActivatingModel_F = self.OM.LoadObj(path)

        self.solution_start = self.ActionData.solution_start
        self.solution_num = self.ActionData.Data.shape[1] - self.ActionData.solution_start

        for i in range (1,4):
            if i == 1:
                char = 'A'
            elif i == 2:
                char = 'S'
            else:
                char = 'F'

            for j in range (0,self.solution_num):
                path = '../model/' + mode + '/Activating_SolutionTrain_' + \
                char + str(j+1) + '.pkl'

                obj = self.OM.LoadObj(path)
                if i == 1:
                    self.Activating_SolutionModel_A.append(obj)
                elif i == 2:
                    self.Activating_SolutionModel_S.append(obj)
                else:
                    self.Activating_SolutionModel_F.append(obj)

        path = '../data/UserData.pkl'
        self.UserData = self.OM.LoadObj(path)

        path = '../data/UnTaggedAction.pkl'
        self.UnTaggedAction = self.OM.LoadObj(path)

        path = '../data/UnTaggedText.pkl'
        self.UnTaggedText = self.OM.LoadObj(path)
    

    def InputSample (self,input_arr): #根据输入构造样本
        dict = {}

        for i in range (0,self.ActionData.Data.shape[1]):
            dict[self.ActionData.Data.iloc[:,i].name] = 0
        
        self.sample = pd.DataFrame ([dict])

        self.sample.iloc[0,0] = 1 - self.identity
        age = self.UserData.UserList[1-self.identity]['Age']

        if age < 18:
            age = 0
        elif age >= 18 and age <= 20:
            age = 1
        elif age >= 21 and age <= 23:
            age = 2
        elif age >= 24 and age <= 27:
            age = 3
        elif age >= 28 and age <= 31:
            age = 4
        elif age >= 32 and age <= 35:
            age = 5
        else:
            age = 6

        self.sample.iloc[0,1] = age

        for i in range (0,len(input_arr)):
            self.sample.iloc[0,5+i] = input_arr[i]

    
    def InputText (self,text): #根据输入文本构造样本
        self.text_sample = self.TextData.TextSample (text)
        self.text_input = text

    
    def ActionAnalysis (self): #通过行为判断情绪
        sub_sample1 = self.sample.iloc[0:1,0:3]
        sub_sample2 = self.sample.iloc[0:1,5:self.solution_start]
        sub_sample = pd.concat ([sub_sample1,sub_sample2],axis=1)
        emotion = self.Action_EmotionModel.Analysis(sub_sample) 
        return emotion
    

    def Analysis (self,emotion1): #情绪判断
        # sub_sample = self.sample.iloc[0:1,0:self.solution_start]
        # emotion1 = self.Action_EmotionModel.Analysis(sub_sample) 
        emotion2 = self.Text_HiddenModel.Analysis(self.text_sample) #预测情绪
        print ('文本分析完成')

        if (emotion1 == 0 or emotion1 == 4) and (emotion2 != 0):
            hidden = 1
        else:
            hidden = 0

        self.sample.iloc[0,2] = emotion1
        self.sample.iloc[0,4] = hidden

        sub_sample = self.sample.iloc[0:1,0:self.solution_start]
        activating = 9

        if emotion1 == 1:
            activating = self.Hidden_ActivatingModel_A.Analysis(sub_sample) #预测原因
        if emotion1 == 2:
            activating = self.Hidden_ActivatingModel_S.Analysis(sub_sample) #预测原因
        if emotion1 == 3:
            activating = self.Hidden_ActivatingModel_F.Analysis(sub_sample) #预测原因
        
        self.sample.iloc[0,3] = activating

        sub_sample = self.sample.iloc[0:1,0:self.solution_start]
        sub_sample['solution'] = 0

        if emotion1 == 1:
            for i in range (0,self.solution_num):
                col = self.Activating_SolutionModel_A[i].data.shape[1]
                new_name = self.Activating_SolutionModel_A[i].data.iloc[:,col-1].name
                sub_sample = self.sample.iloc[0:1,0:self.solution_start]
                sub_sample[new_name] = 0
                solution = self.Activating_SolutionModel_A[i].Analysis(sub_sample) #预测解决方法
                self.sample.iloc[0,self.solution_start+i] = solution

        if emotion1 == 2:
            for i in range (0,self.solution_num):
                col = self.Activating_SolutionModel_S[i].data.shape[1]
                new_name = self.Activating_SolutionModel_S[i].data.iloc[:,col-1].name
                sub_sample = self.sample.iloc[0:1,0:self.solution_start]
                sub_sample[new_name] = 0
                solution = self.Activating_SolutionModel_S[i].Analysis(sub_sample) #预测解决方法
                self.sample.iloc[0,self.solution_start+i] = solution

        if emotion1 == 3:
            for i in range (0,self.solution_num):
                col = self.Activating_SolutionModel_F[i].data.shape[1]
                new_name = self.Activating_SolutionModel_F[i].data.iloc[:,col-1].name
                sub_sample = self.sample.iloc[0:1,0:self.solution_start]
                sub_sample[new_name] = 0
                solution = self.Activating_SolutionModel_F[i].Analysis(sub_sample) #预测解决方法
                self.sample.iloc[0,self.solution_start+i] = solution


    def ResultText (self): #生成结果文字
        target = (1-self.identity)
        user_info = self.UserData.UserList[self.identity]
        target_info = self.UserData.UserList[target]

        target_name = user_info['Nickname']
        target_sex = target
        hidden = self.sample.iloc[0,4]
        emotion = self.sample.iloc[0,2]
        activating = self.sample.iloc[0,3]
        s_list = []

        if target_sex == 0:
            s_text = '他'
        else:
            s_text = '她'

        if emotion == 1:
            e_text = '烦躁'
        elif emotion == 2:
            e_text = '伤心'
        elif emotion == 3:
            e_text = '焦虑'

        if hidden == 0:
            h_text = '展示'
        else:
            h_text = '隐藏'

        a_text = self.ActionData.activatings[activating]

        for i in range (0,self.solution_num):
            if self.sample.iloc[0,self.solution_start+i] == 1:
                s_list.append(i)

        if len(s_list) == 1:
            r1 = 0
            r2 = -1
            s1_text = self.ActionData.solutions[s_list[r1]]
    
        elif len(s_list) == 0:
            r1 = -1
            r2 = -1
        else:
            r2 = random.randint (0,len(s_list)-1)
            r1 = r2

            while r2 == r1:
                r1 = random.randint(0,len(s_list)-1)
            
            s1_text = self.ActionData.solutions[s_list[r1]]
            s2_text = self.ActionData.solutions[s_list[r2]]

        if emotion == 0:
            r_text = target_name + '好像挺开心的\n' + '他似乎向您' + h_text + '了这种情绪\n' + '快和' + \
            target_name + '一起分享喜悦吧！'

        elif emotion == 4:
            r_text = target_name + '好像很平静呢\n' + '快去陪' + target_name + '说说话吧！'

        else:

            if r1 == -1:
                r_text = target_name + '好像正在' + e_text + '\n' + s_text + '似乎向您' + h_text + \
                '了这种情绪\n 这种情绪可能是因为' + a_text + '引起的\n 您可以尝试陪' + s_text + '说说话哦！'

            elif r2 == -1:
                r_text = target_name + '好像正在' + e_text + '\n' + s_text + '似乎向您' + h_text + \
                '了这种情绪\n 这种情绪可能是因为' + a_text + '引起的\n 您可以' + s1_text + '哦！'

            else:
                r_text = target_name + '好像正在' + e_text + '\n' + s_text + '似乎向您' + h_text + \
                '了这种情绪\n 这种情绪可能是因为' + a_text + '引起的\n 您可以' + s1_text + '或者' + s2_text \
                + '哦！'

        self.sample['Sample_id'] = self.UnTaggedAction.next_id
        self.sample['Result_Text'] = r_text
        self.text_sample['Sample_id'] = self.UnTaggedText.next_id
        self.text_sample['Text'] = self.text_input

        return r_text


    def UpdateUntagged (self): #更新未贴标签的数据
        col_name_list = list (self.UnTaggedAction.Data)

        dict = {}

        for i in range (0,len(col_name_list)):
            dict[col_name_list[i]] = 0

        output_sample = pd.DataFrame([dict]) #构造空行为样本

        col_name_list = list (self.UnTaggedText.Data)

        dict = {}

        for i in range (0,len(col_name_list)):
            dict[col_name_list[i]] = 0

        output_text_sample = pd.DataFrame([dict]) #构造空文本样本

        for i in range (0,self.sample.shape[1]): #构造完整输出样本
            col_name = self.sample.iloc[:,i].name
            output_sample[col_name] = self.sample.iloc[0,i]

        for i in range (0,self.text_sample.shape[1]): #构造完整输出样本
            col_name = self.text_sample.iloc[:,i].name
            output_text_sample[col_name] = self.text_sample.iloc[0,i]

        self.UnTaggedAction.AddSample (output_sample)
        self.UnTaggedText.AddSample (output_text_sample)

        path = './data/UnTaggedAction.pkl'
        self.OM.SaveObj(self.UnTaggedAction,path)

        path = './data/UnTaggedText.pkl'
        self.OM.SaveObj(self.UnTaggedText,path)